const WS = require('ws');

class Websocket {
    ws;
    qiuya;

    constructor(qiuya) {
        this.qiuya = qiuya;
        this.init();
    }

    init(){
        const ws = this.ws = new WS(`ws://${this.qiuya.url}/websocket/`);
        ws.on('open', () => {
            this.qiuya.connectionPool.push(ws);
            this.qiuya.emitter.emit("GET_CONNECTION")
        });
        ws.on('message', (data) => {
            var i = data.indexOf(" ");
            if(i === -1){
                return
            }
            var flag = data.substring(0, i);
            if(flag !== "ack"){
                return;
            }
            var i1 = data.indexOf(" ", i + 1)
            if(i1 === -1){
                return;
            }
            var ack = data.substring(i + 1, i1)
            var msg = data.substring(i1 + 1)
            this.qiuya.emitter.emit(ack, msg);
            // this.qiuya._onMessage(ack, msg)
        });
        ws.on("error", () => {
            this.reconnect()
        });
        ws.on("close", () => {
            this.reconnect()
        })
    }

    reconnect(){
        var i = this.qiuya.connectionPool.indexOf(this.ws);
        if(i > -1){
            this.qiuya.connectionPool.splice(i, 1);
        }
        setTimeout(() => {
            this.init();
        },1000)
    }
}

module.exports = Websocket